package com.demo.swingquickticket.util.http;

import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.http.Consts.UTF_8;

@Data
public class RequestEntity {

    public RequestEntity(String url, String requestType) {
        this.url = url;
        this.requestType = requestType;
        this.httpResult = (request, response) -> response;
    }

    //请求结果返回后的处理
    private HttpResult httpResult;

    //请求地址
    private String url;

    //请求头
    private Map<String, String> headers;

    //请求类型
    private String requestType;

    //请求参数
    private Map<String, String> params;

    //请求参数体
    private String paramBody;

    //请求代理
    private HttpHost httpHost;

    //返回字符集
    private Charset charset = UTF_8;

    //网页请求cookie
    private Cookie[] cookies;

    //cookie存储
    private BasicCookieStore cookieStore;

    //请求体
    private CloseableHttpClient httpClient;

    public void addParam(String key, String value) {
        if (params == null) {
            params = new HashMap<>();
        }
        params.put(key, value);
    }

    public void removeParam(String key) {
        if (params != null) {
            params.remove(key);
        }
    }

    public void clearParams() {
        this.params = null;
        this.paramBody = null;
    }

    public void addHeader(String key, String value) {
        if (headers == null) {
            headers = new HashMap<>();
        }
        headers.put(key, value);
    }

    public void removeHeader(String key) {
        if (headers != null) {
            headers.remove(key);
        }
    }



    public void setCookieList(List<Cookie> cookieList) {
        if (cookieList != null) {
            this.cookies = cookieList.toArray(new Cookie[0]);
        }
    }

    public void buildHttpClient() {
        if (this.cookieStore == null) {
            this.cookieStore = new BasicCookieStore();
            cookieStore.addCookies(this.cookies);
        }
        this.httpClient = HttpClients
                .custom()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectTimeout(10000)//10秒超时
                        .setConnectionRequestTimeout(10000)//10秒超时
                        .build())
                .setDefaultCookieStore(cookieStore)//设置Cookie
                .build();
    }
}
